package com.ruoyi.web.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.RedissonLockComponent;
import com.ruoyi.system.domain.Product;
import com.ruoyi.system.domain.ProductKey;
import com.ruoyi.system.mapper.ProductMapper;
import com.ruoyi.web.service.ISysProductKeySevice;
import com.ruoyi.web.service.ISysProductSevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
public class SysProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ISysProductSevice {

    @Autowired
    private RedissonLockComponent redissonLockComponent;

    @Autowired
    private ISysProductKeySevice sysProductKeySevice;

    @Override
    @Transactional
    public void updateStockHasLock(List<Long> productIds) {
        if (CollectionUtil.isEmpty(productIds)) {
            return;
        }
        productIds.parallelStream().forEach(productId -> {
            Product product = this.getById(productId);
            if (Objects.isNull(product)) {
                return;
            }
            redissonLockComponent.execByDistributedLock("update_stock:" + productId, 2L ,() -> {
                List<ProductKey> productKeys = sysProductKeySevice.queryNotSelledProductKey(productId);
                this.update(
                        Wrappers.lambdaUpdate(Product.class)
                                .eq(Product::getId, productId)
                                .set(Product::getStock, productKeys.size())
                );
                return true;
            });
        });
    }

    @Override
    public void updateStockNoLock(List<Long> productId) {
        if (CollectionUtil.isEmpty(productId)) {
            return;
        }
        productId.forEach(id -> {
            List<ProductKey> productKeys = sysProductKeySevice.queryNotSelledProductKey(id);
                this.update(
                        Wrappers.lambdaUpdate(Product.class)
                                .eq(Product::getId, id)
                                .set(Product::getStock, productKeys.size())
                );
        });
    }

    @Override
    public List<Product> queryByCategoryId(List<Long> ids) {
        return this.list(
                Wrappers.lambdaQuery(Product.class)
                        .in(Product::getCategoryId, ids)
        );
    }
}
